package com.shelpe.services.auth.service;

import com.shelpe.services.auth.entity.AuthInfo;
import com.shelpe.services.auth.entity.Users;
import com.shelpe.services.auth.repository.AuthRepository;
import com.shelpe.services.auth.repository.UsersRepository;

import lombok.Setter;

@Setter
public class TokenServiceImpl implements TokenService {

	private AuthRepository authRepository;
	
	private UsersRepository usersRepository;

	@Override
	public UserInfo getToken(String nick) {
		UserInfo info = new UserInfo();
		
		Users user = usersRepository.findTopByNickOrderByUserIdDesc(nick);
		info.setUser(user);
		if(user != null){
			info.setAuth(this.findAuthInfo(user));
		}
		return info;
	}

	@Override
	public UserInfo getToken(long userId) {
		UserInfo info = new UserInfo();
		
		Users user = usersRepository.findTopByUserId(userId);
		info.setUser(user);
		if(user != null){
			info.setAuth(this.findAuthInfo(user));
		}
		return info;
	}
	
	private AuthInfo findAuthInfo(Users user){
		String authorizedTo = user.getAuthorizedTo();
		if(authorizedTo.equals("0")){
			authorizedTo = user.getUserId().toString();
		}
		return authRepository.findByTaobaoUserId(authorizedTo);
	}

}
